package exts

import (
	"context"
	"errors"
	"gitee.com/tietang/terrace-go/v2/base/plugin"
	"gitee.com/tietang/terrace-go/v2/example/order"
	"time"
)

var defaultExt order.CreateOrderDomainExt = new(DefaultOrderCreatedDomainExt)
var _ plugin.PluginId = new(DefaultOrderCreatedDomainExt)

func init() {
	plugin.Register(defaultExt)
}

type DefaultOrderCreatedDomainExt struct {
	order.CreateOrderDomainExt
}

func (o *DefaultOrderCreatedDomainExt) OnValidate(ctx context.Context, in *order.Order) error {

	if !in.TradeAmount.Equal(in.PayAmount) {
		return errors.New("交易金额和支付金额不一致")
	}
	return nil
}

func (o *DefaultOrderCreatedDomainExt) PreSave(ctx context.Context, in *order.Order) error {
	//默认为下单状态
	in.Status = 0
	//默认凌晨4点之前算前一天营业日
	date := time.Now()
	date.Add(-time.Hour * 4)
	in.BizDate = &date
	return nil
}

func (o *DefaultOrderCreatedDomainExt) Check(ctx context.Context, in interface{}) bool {
	dto := in.(*order.Order)
	return dto.Source == 0
}

func (o *DefaultOrderCreatedDomainExt) PluginCode() string {
	return order.CreateOrderDomainPluginId
}
func (o *DefaultOrderCreatedDomainExt) Ability() string {
	return "default"
}
